import 'dart:convert';
import 'dart:io';

import 'package:get/get.dart';
import 'package:zz_video_maker/zz_video_maker.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path/path.dart';

abstract class EditedDataController extends GetxController {
  final bool isAsset;
  final String path;
  AllEditedData? allEditedData;
  static const initializedDataId = "initializedData";

  EditedDataController({required this.isAsset, required this.path});

  @override
  void onInit() {
    super.onInit();
    init();
  }

  Future<void> init() async {
    String jsonString;
    if (isAsset) {
      jsonString = await rootBundle.loadString(path);
    } else {
      jsonString = await File(path).readAsString();
    }

    final exportedJSON = json.decode(jsonString);

    if (isAsset) {
      List slides = exportedJSON["timeline"]["slides"];
      List bgm = exportedJSON["timeline"]["bgm"];

      for (int i = 0; i < slides.length; i++) {
        final String filename = basename(slides[i]["localPath"]);

        final writeFile =
            await copyAssetToLocalDirectory("test/set1/$filename");
        slides[i]["localPath"] = writeFile.path;
      }

      for (int i = 0; i < bgm.length; i++) {
        final String filename = basename(bgm[i]["sourcePath"]);

        final writeFile =
            await copyAssetToLocalDirectory("raw/audio/$filename");
        bgm[i]["sourcePath"] = writeFile.path;
      }
    }

    var allEditedData = parseJSONToAllEditedData(json.encode(exportedJSON));
    this.allEditedData = allEditedData;
    List<EditedTextData> texts = [];
    for (var i = 0; i < allEditedData.editedMediaList.length; i++) {
      EditedMedia editedMedia = allEditedData.editedMediaList[i];
      if (editedMedia.editedTexts.isNotEmpty) {
        texts.addAll(editedMedia.editedTexts);
      }
    }

    await initializeDataComplete();
  }

  initializeDataComplete();
}
